package com.ajie.utils;

import com.ajie.config.BeanConfig;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 七牛云文件上传工具类
 */
@Component
@Slf4j
public class QiniuUtils {

    @Value("${qiniu.accessKey}")
    private String accessKey;
    
    @Value("${qiniu.secretKey}")
    private String secretKey;
    
    @Value("${qiniu.bucket}")
    private String bucket;
    
    @Autowired
    private UploadManager uploadManager;
    
    /**
     * 鉴权，返回鉴权字符串
     * @return
     */
    public String upToken(){
        log.info("该文件名是：QiniuUtils,该方法是：upToken");
        Auth auth = Auth.create(accessKey,secretKey);
        return auth.uploadToken(bucket);
    }
    
    
    /**
     * 根据路径上传文件
     * @param filePath
     * @param fileName
     * @return
     */
    public String uploadQiniu(String filePath, String fileName){
        log.info("该文件名是：QiniuUtils,该方法是：uploadQiniu");
        
        String key = fileName;
        String name = this.genName(fileName);
        try {
            Response response = uploadManager.put(filePath, name, this.upToken());
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
            log.info("文件上传成功==>key{},==>hash:{}" , putRet.key, putRet.hash);
            return name;
        } catch (QiniuException e) {
            Response r = e.response;
            try {
                log.error("文件上传失败==>{}",r.bodyString());
            } catch (QiniuException ex) {
            }
            return null;
        }
    }
    
    
    /**
     * 根据字节上传文件
     * @param bytes
     * @param fileName
     * @return
     */
    public String uploadQiniu(byte[] bytes, String fileName){
        log.info("该文件名是：QiniuUtils,该方法是：uploadQiniu1");
        String key = fileName;
        String name = this.genName(fileName);
        try {
            Response response = uploadManager.put(bytes, name, this.upToken());
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
            log.info("文件上传成功==>key{},==>hash:{}" , putRet.key, putRet.hash);
            return name;
        } catch (QiniuException e) {
            Response r = e.response;
            try {
                log.error("文件上传失败==>{}",r.bodyString());
            } catch (QiniuException ex) {
            }
            return null;
        }
    }
    
    
    /**
     * 根据字节上传文件
     * @param stream
     * @param fileName
     * @return
     */
    public String uploadQiniu(InputStream stream, String fileName){
        log.info("该文件名是：QiniuUtils,该方法是：uploadQiniu");
        String key = fileName;
        /**
         * 文件输入流上传文件
         */
        String name = this.genName(fileName);
        try {
            Response response = uploadManager.put(stream, name, this.upToken(),null,null);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
            log.info("文件上传成功==>key{},==>hash:{}" , putRet.key, putRet.hash);
            return name;
        } catch (QiniuException e) {
            Response r = e.response;
            try {
                log.error("文件上传失败==>{}",r.bodyString());
            } catch (QiniuException ex) {
            }
            return null;
        }
    }
    
    
    /**
     * 根据文件名生成时间文件名
     * @param fileName
     * @return
     */
    public String genName(String fileName){
        log.info("该文件名是：QiniuUtils,该方法是：genName");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        return format.format(new Date()) + fileName;
    }
    
    
    /**
     * 根据文件名删除文件
     * @param fileName
     */
    public void delete(String fileName){
        log.info("该文件名是：QiniuUtils,该方法是：delete");
        Configuration cfg = new Configuration(Region.region2());
        Auth auth = Auth.create(accessKey,secretKey);
        BucketManager bucketManager = new BucketManager(auth,cfg);
        try {
            bucketManager.delete(bucket,fileName);
        } catch (QiniuException e) {
            log.error("删除失败==>code{}"+ e.code());
            log.error(e.response.toString());
        }
    }
}
